#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>

#include <unistd.h>
#include <fcntl.h>
#include <sys/resource.h>
#include <syslog.h>

void daemonize() {
	int pid;
	int i;
	struct rlimit rlmt;

	if ((pid=fork()) > 0)	{
		printf("main exit\n");
		exit(0);
	}
	else if (pid < 0) {
		printf("fork error\n");
		exit(1);
	}
	else {
		setsid();
		if ((pid=fork()) > 0)	{
			printf("child 1 exit\n");
			exit(0);
		}
		else if (pid < 0) {
			printf("fork 1 error\n");
			exit(1);
		}
		else {
			getrlimit(RLIMIT_NOFILE, &rlmt);
			if (rlmt.rlim_max == RLIM_INFINITY)
				rlmt.rlim_max = 1024;
			for (i=0; i<rlmt.rlim_max; i++)
				close(i);

			chdir("/");
			umask(0);
			return;
		}
	}

}

int main() {
	FILE* fp;
	time_t t;
	daemonize();
printf("ret\n");
	while (1) {
		sleep(10);
		if ((fp=fopen("test.log", "a")) >= 0) {
			t = time(0);
			fprintf(fp, "here at %s\n", asctime(localtime(&t)));
			fclose(fp);
		}
	}
	return 0;
}